package org.kl.auditsupervision.web.fnd;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.kl.bf.entity.easyui.EasyuiUtils;
import org.kl.bf.utils.KLServlets;
import org.kl.bf.web.base.BasicController;
import org.kl.auditsupervision.entity.fnd.Employee;
import org.kl.auditsupervision.service.fnd.EmployeeService;
import org.kl.auditsupervision.service.fnd.OrgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.MediaTypes;

/**
 * @author Code Generator
 * @since  2015-09-09 09:42:17
 * @see 人员信息表  人员信息表
 */
@Controller
@RequestMapping(value = "/fnd/employee")
public class EmployeeController extends BasicController {

	@Autowired
	private EmployeeService employeeService;
	@Autowired
	private OrgService orgService;
	
	@RequiresPermissions(value = "employee:list")
	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return "fnd/employeeList";
	}

	@RequestMapping(value = "dataGrid", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String dataGrid(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "rows", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sort", defaultValue = "org.orgName,orderNo") String sortType,
			@RequestParam(value = "order", defaultValue = "asc,asc") String orderType, Model model, ServletRequest request) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		Page<Employee> employee = employeeService.getPage(searchParams, pageNumber, pageSize, sortType,orderType);
		return EasyuiUtils.buildEasyuiGridJsonString(employee.getContent(), (int) employee.getTotalElements());
	}
	
	@RequestMapping(value = "dataGridFilter", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String dataGridFilter(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "rows", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sort", defaultValue = "org.orgName,orderNo") String sortType,
			@RequestParam(value = "order", defaultValue = "asc,asc") String orderType, Model model, ServletRequest request) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		String orgId="",allChildOrgId="";
		if(!isPermission("employee"+":allQuery")){
			orgId=BasicController.getCurrentUserDeptId();
			orgId=orgService.getAllChildOrgId(orgId, allChildOrgId)+","+orgId;
			if(searchParams.containsKey("IN_org.id")){				
				searchParams.remove("IN_org.id");				
			}
			searchParams.put("IN_org.id",orgId);
		}else{
			
		}
		Page<Employee> employee = employeeService.getPage(searchParams, pageNumber, pageSize, sortType,orderType);
		return EasyuiUtils.buildEasyuiGridJsonString(employee.getContent(), (int) employee.getTotalElements());
	}
	
	
	@RequestMapping(value = "dataGridChilrenEmp", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String dataGridChilrenEmp(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "rows", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sort", defaultValue = "org.orgName,orderNo") String sortType,
			@RequestParam(value = "order", defaultValue = "asc,asc") String orderType, Model model, ServletRequest request) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		String orgId="",allChildOrgId="";
		if(searchParams.containsKey("IN_org.id")){
			orgId=searchParams.get("IN_org.id").toString();
			orgId=orgService.getAllChildOrgId(orgId, allChildOrgId)+","+orgId;
			searchParams.remove("IN_org.id");
			searchParams.put("IN_org.id",orgId);
		}
		Page<Employee> employee = employeeService.getPage(searchParams, pageNumber, pageSize, sortType,orderType);
		return EasyuiUtils.buildEasyuiGridJsonString(employee.getContent(), (int) employee.getTotalElements());
	}
	
	@RequiresPermissions(value = "employee:update")
	@RequestMapping(value = "update", method = RequestMethod.POST, produces = { MediaTypes.TEXT_HTML_UTF_8,
			MediaTypes.JSON_UTF_8 })
	@ResponseBody
	public String update(@Valid @ModelAttribute("employee") Employee employee, @RequestParam(value = "detailInserted",defaultValue="") String detailInserted,
			@RequestParam(value = "detailUpdated",defaultValue="") String detailUpdated, @RequestParam(value = "detailDeleted",defaultValue="") String detailDeleted, BindingResult result) {
		if(result.hasErrors()){
			return ajaxMsg(bindingMsg(result), false, null);
		}
		try{
			if(employee.getOrg()!=null&&StringUtils.isBlank(employee.getOrg().getId())){
				return ajaxMsg("保存失败，组织机构不能为空", false, null);
			}
			employeeService.save(employee, detailInserted, detailUpdated, detailDeleted);
		    return ajaxMsg("保存成功", true, null);
		}catch(Exception e){
			e.printStackTrace();
			return ajaxMsg("保存失败", false, null);
		}
	}
	
	@RequestMapping(value = "fpUser", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String fpUser(@RequestParam(value = "ids", defaultValue = "") String ids) {
		String msg = "";
		try {
			msg = employeeService.fpUser(ids);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("分配失败:" + e.getMessage(), false, null);
		}
		return ajaxMsg("分配成功:" + msg, true, null);
	}
	
	@RequiresPermissions(value = "employee:delete")
	@RequestMapping(value = "delete/{id}", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String delete(@PathVariable("id") String id, RedirectAttributes redirectAttributes) {
		try {
			employeeService.delete(id);
			return ajaxMsg("删除成功", true, null);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("删除失败", false, null);
		}
	}
	
	@RequiresPermissions({ "employee:delete" })
	@RequestMapping(value = "multiDelete", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String multiDelete(@RequestParam(value = "ids", defaultValue = "") String ids) {
		String msg = "";
		try {
			msg = employeeService.multiDelete(ids);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("删除失败:" + e.getMessage(), false, null);
		}
		return ajaxMsg("删除成功:" + msg, true, null);
	}
	
	@RequiresPermissions("employee:export")
	@RequestMapping(value = "excelExport", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String excelExport(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		String orgId="",allChildOrgId="";
		if(searchParams.containsKey("IN_org.id")){
			orgId=searchParams.get("IN_org.id").toString();
			orgId=orgService.getAllChildOrgId(orgId, allChildOrgId)+","+orgId;
			searchParams.remove("IN_org.id");
			searchParams.put("IN_org.id",orgId);
		}

		List<Employee> employee = employeeService.searchAll(searchParams, sortType, orderType);
		String employeeIds="";
		for(Employee e :employee){
			employeeIds=employeeIds==""?e.getId():employeeIds+","+e.getId();
		}
		
		super.export(Employee.class, response, employee, "人员信息表");
		return null;
	}

	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出Task对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 */
	@ModelAttribute
	public void init(@RequestParam(value = "id", defaultValue = "-1") String id, Model model) {
		if (!id.equals("-1")) {
			model.addAttribute("employee", employeeService.findOneAndClear(id));
		}
	}
	
	
	
	
}



